package com.itheima.health.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.itheima.health.dto.ExcelDTO;
import com.itheima.health.mapper.OrderSettingMapper;
import com.itheima.health.pojo.OrderSetting;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
public class MyExcelListener implements ReadListener<ExcelDTO> {
    private static final int BATCH_COUNT = 10;
    private OrderSettingMapper orderSettingMapper;

    //缓冲池
    private List<OrderSetting> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public MyExcelListener() {
    }

    public MyExcelListener(OrderSettingMapper orderSettingMapper) {
        this.orderSettingMapper = orderSettingMapper;
    }

    @SneakyThrows
    @Override
    public void invoke(ExcelDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", data);

        String dateStr = data.getDate();
        //原格式
        Date parse = new SimpleDateFormat("yyyy/MM/dd").parse(dateStr);
        //目标格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(parse);
        Date date = simpleDateFormat.parse(format);

        //防止触发唯一性约束
        Integer count = orderSettingMapper.selectCountByDate(date);
        if (count == 0){
            OrderSetting build = OrderSetting.builder()
                    .orderDate(date)
                    .number(data.getNumber()).build();

            cachedDataList.add(build);
        }

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据太多造成OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        if (!cachedDataList.isEmpty()){
            orderSettingMapper.insertBeatch(cachedDataList);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("解析完成");
    }
}
